﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using SCM.Common.Extensions;
using SCM.Model;
using SCM.Servie.IBusiness;

namespace SCM.Manage.Controllers
{
    public class LoginController : BaseController
    {
        private readonly IUserService _userService;
        private readonly ICompanyService _companyService;

        public LoginController(IUserService userService, ICompanyService companyService)
        {
            this._userService = userService;
            this._companyService = companyService;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Index(string phone, string passWord)
        {
            if (string.IsNullOrWhiteSpace(phone))
            {
                return Error("登录失败，手机号不能为空");
            }
            if (string.IsNullOrWhiteSpace(passWord))
            {
                return Error("登录失败，密码不能为空");
            }

            var userVo = _userService.Login(phone, EncryptHelper.HashMD5String(passWord, Encoding.UTF8));
            if (userVo == null)
            {
                return Error("登录失败，手机号与密码不匹配");
            }
            else
            {
                if (userVo.ValidDate < DateTime.Now)
                {
                    return Error("当前帐号已过期，请联系平台处理");
                }

                var claims = new List<Claim>(){
                    new Claim(ClaimTypes.Sid,userVo.UserID),
                    new Claim(ClaimTypes.Name,userVo.UserDisplayName),
                    new Claim(ClaimTypes.Role,userVo.RoleNameDescription),
                    new Claim("RoleID",userVo.RoleID),
                    new Claim("CompanyID",userVo.CompanyID),
                    new Claim("CompanyName",userVo.CompanyName),
                 };
                var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "User"));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });
                return GetOk("/home");
            }
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public IActionResult SubmitRegiste(LoginRegisteVo model)
        {
            #region 数据检查
            var company = _companyService.Get(model.CompanyName, model.IdentityNumber, model.TelPhone, model.Email);
            if (company != null)
            {
                return Error("企业已注册");
            }

            var role = GetService<IRoleService>().GetByRoleName("Admin");
            if (role == null)
            {
                return Error("初始化权限失败");
            }

            model.UserPassword = EncryptHelper.HashMD5String(model.UserPassword);
            model.DataStatus = DataStatusEnum.Valid;
            model.UserType = UserTypeEnum.General;
            model.ValidDate = DateTime.Now.AddMonths(1);
            model.RoleID = role.ID;
            model.Creator = "system";
            model.CreatorName = "system";
            #endregion

            var result = _userService.Registe(model);
            return result ? GetOk("/Login") : Error("注册失败");
        }
    }
}
